package com.cobra.provider.service;

import com.cobra.DemoService;
import com.cobra.DemoServiceListener;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Service(version = "callback", methods = {@Method(name = "sayHello", arguments = {@Argument(index = 2, callback = true)})}, callbacks = 3)
public class CallBackDemoService implements DemoService {

    private final Map<String, DemoServiceListener> listeners = new ConcurrentHashMap<String, DemoServiceListener>();
    public CallBackDemoService() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (!listeners.isEmpty()) {
                        System.out.println(listeners.size());
                        for (Map.Entry<String, DemoServiceListener> entry : listeners.entrySet()) {
                            entry.getValue().changed(getChanged(entry.getKey()));
                        }
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        t.start();

    }
    private String getChanged(String key) {
        return "Changed: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
    @Override
    public String sayHello(String name) {
        return null;
    }

    @Override
    public String sayHello(String name, String key, DemoServiceListener listener) {
        System.out.println("执行了回调服务" + name);
        //将消费端声明的回调接口生成代理对象传给消费端进行执行下述的逻辑
        listener.changed("xxxx");

        listeners.put(key, listener);
        URL url = RpcContext.getContext().getUrl();
        return String.format("执行方法回调:   %s：%s, Hello, %s", url.getProtocol(), url.getPort(), name);
    }
}
